package logics

import (
	"context"
	"fmt"
	"git.900sui.cn/kc/kcgin/logs"
	"reflect"
	"strconv"
	"time"

	"git.900sui.cn/kc/base/common/toolLib"
	"git.900sui.cn/kc/kcgin"
	"git.900sui.cn/kc/mapstructure"
	"git.900sui.cn/kc/redis"
	pay2 "git.900sui.cn/kc/rpcPay/common/lib/pay"
	"git.900sui.cn/kc/rpcPay/common/logics/fund"
	"git.900sui.cn/kc/rpcPay/common/models"
	"git.900sui.cn/kc/rpcPay/constkey"
	_const "git.900sui.cn/kc/rpcPay/lang/const"
	"git.900sui.cn/kc/rpcinterface/client/bus"
	"git.900sui.cn/kc/rpcinterface/client/order"
	pay3 "git.900sui.cn/kc/rpcinterface/client/task/pay"
	bus2 "git.900sui.cn/kc/rpcinterface/interface/bus"
	order2 "git.900sui.cn/kc/rpcinterface/interface/order"
	"git.900sui.cn/kc/rpcinterface/interface/pay"
	"github.com/shopspring/decimal"
	"github.com/tidwall/gjson"
)

type PayLogic struct {
}

// 支付二维码
func (p *PayLogic) PayQr(payInfo *pay.PayInfo) (string, error) {
	res := p.getCache(payInfo, "PayQr")
	if res == nil {
		payLib, err := pay2.GetPay(payInfo.PayChannel)
		if err != nil {
			return "", err
		}
		result, err := (*payLib).PayQr(payInfo)
		_ = p.setCache(payInfo, "PayQr", result)
		return result, err
	} else {
		return string(res.([]byte)), nil
	}
}

// h5支付连接
func (p *PayLogic) PayH5(payInfo *pay.PayInfo) (string, error) {
	res := p.getCache(payInfo, "PayH5")
	if res == nil {
		payLib, err := pay2.GetPay(payInfo.PayChannel)
		if err != nil {
			return "", err
		}
		result, err := (*payLib).PayH5(payInfo)
		_ = p.setCache(payInfo, "PayH5", result)
		return result, err
	} else {
		return string(res.([]byte)), nil
	}
}

//PayH5New h5支付数据
func (p *PayLogic) PayH5New(payInfo *pay.PayInfo) (s *pay.PayH5, err error) {
	payLib, err := pay2.GetPay(payInfo.PayChannel)
	if err != nil {
		return s, err
	}
	payH5 := &pay.PayH5{}
	err = (*payLib).PayH5New(payInfo, payH5)
	return payH5, err
}

// wx小程序支付信息
func (p *PayLogic) PayWxApp(payInfo *pay.PayInfo) (*gjson.Result, error) {
	res := p.getCache(payInfo, "PayWxApp")
	if res == nil {
		payLib, err := pay2.GetPay(payInfo.PayChannel)
		if err != nil {
			return nil, err
		}
		result, err := (*payLib).PayWxApp(payInfo)
		_ = p.setCache(payInfo, "PayWxApp", result)
		return result, err
	} else {
		gRes := gjson.ParseBytes(res.([]byte))
		return &gRes, nil
	}

}

// 微信公众号支付数据
func (p *PayLogic) PayWxOfficial(payInfo *pay.PayInfo) (*gjson.Result, error) {
	res := p.getCache(payInfo, "PayWxOfficial")
	if res == nil {
		payLib, err := pay2.GetPay(payInfo.PayChannel)
		if err != nil {
			return nil, err
		}
		result, err := (*payLib).PayWxOfficial(payInfo)
		_ = p.setCache(payInfo, "PayWxOfficial", result)
		return result, err
	} else {
		gRes := gjson.ParseBytes(res.([]byte))
		return &gRes, nil
	}
}

// app支付信息
func (p *PayLogic) PayApp(payInfo *pay.PayInfo) (*gjson.Result, error) {
	res := p.getCache(payInfo, "PayApp")
	if res == nil {
		payLib, err := pay2.GetPay(payInfo.PayChannel)
		if err != nil {
			return nil, err
		}
		result, err := (*payLib).PayApp(payInfo)
		_ = p.setCache(payInfo, "PayApp", result)
		return result, err
	} else {
		gRes := gjson.ParseBytes(res.([]byte))
		return &gRes, nil
	}
}

func (p *PayLogic) PayAppSign(payInfo *pay.PayInfo) (string, error) {
	res := p.getCache(payInfo, "PayAppSign")
	if res == nil {
		payLib, err := pay2.GetPay(payInfo.PayChannel)
		if err != nil {
			return "", err
		}
		result, err := (*payLib).PayAppSign(payInfo)
		if len(result) == 0 {
			return "", nil
		}
		_ = p.setCache(payInfo, "PayAppSign", result)
		return result, err
	} else {
		return res.(string), nil
	}
}

// 异步回调
func (p *PayLogic) Notify(ctx context.Context, data *pay.ArgsNotify) error {
	payLib, err := pay2.GetPay(data.PayChannel)
	if err != nil {
		return err
	}
	notify, err := (*payLib).Notify(data.Data)
	if err != nil {
		return err
	}
	payNotifyModel := new(models.PayNotifyModel).Init()
	if len(payNotifyModel.GetByOrderSn(notify.OrderSn)) == 0 {
		payNotifyModel.Insert(map[string]interface{}{
			payNotifyModel.Field.F_order_sn:    notify.OrderSn,
			payNotifyModel.Field.F_pay_sn:      notify.PaySn,
			payNotifyModel.Field.F_pay_channel: notify.PayChannel,
			payNotifyModel.Field.F_pay_type:    notify.PayType,
			payNotifyModel.Field.F_pay_amount:  notify.PayAmount,
			payNotifyModel.Field.F_pay_fee:     notify.PayFee,
			payNotifyModel.Field.F_pay_time:    notify.PayTime,
			payNotifyModel.Field.F_pay_status:  notify.PayStatus,
			payNotifyModel.Field.F_create_time: time.Now().Unix(),
			payNotifyModel.Field.F_pay_raw:     data.Data,
		})
		rpcTaskPay := new(pay3.Pay).Init()
		res := false
		if err := rpcTaskPay.PaySuc(ctx, &notify.OrderSn, &res); err != nil {
			return err
		}
	}
	return nil
}

//异步回调响应
func (p *PayLogic) NotifyResponse(ctx context.Context, args *pay.ArgsNotify) (res string, err error) {
	payLib, err := pay2.GetPay(args.PayChannel)
	if err != nil {
		return
	}
	reply, err := (*payLib).NotifyResponse(ctx, args)
	res = reply.ResponseJsonStr
	if err != nil {
		return
	}
	return
}

// 获取支付信息
func (p *PayLogic) PayInfo(orderSn string) (*pay.PayNotify, error) {
	payNotifyModel := new(models.PayNotifyModel).Init()
	res := payNotifyModel.GetByOrderSn(orderSn)
	if len(res) == 0 {
		return nil, toolLib.CreateKcErr(_const.NOT_FIND_PAY_ORDER)
	}
	PayNotify := &pay.PayNotify{}
	if err := mapstructure.WeakDecode(res, PayNotify); err != nil {
		return nil, err
	}
	return PayNotify, nil
}

// 验证空接口类型的值是否为nil
func (p *PayLogic) interfaceIsNil(i interface{}) bool {
	ret := i == nil
	if !ret { //需要进一步做判断
		defer func() {
			recover()
		}()
		ret = reflect.ValueOf(i).IsNil() //值类型做异常判断，会panic的
	}
	return ret
}

//获取缓存
func (p *PayLogic) getCache(payInfo *pay.PayInfo, payType string) interface{} {
	//杉德支付的二维码支付链接支付宝和微信相同，为了解决相同订单号重复提交，把ChosePayType改成0
	if payInfo.PayChannel == order2.PAY_CHANNEL_sand {
		if payInfo.ChosePayType == order2.CHOSE_PAY_TYPE_ALI || payInfo.ChosePayType == order2.CHOSE_PAY_TYPE_WX {
			payInfo.ChosePayType = 0
		}
	}
	key := fmt.Sprintf(constkey.PAY_CACHE, payInfo.OrderSn, payType, payInfo.PayChannel, payInfo.ChosePayType)
	res, _ := redis.RedisGlobMgr.Get(key)
	return res
}

//设置缓存
func (p *PayLogic) setCache(payInfo *pay.PayInfo, payType string, data interface{}) error {
	//验证空接口值的类型
	if p.interfaceIsNil(data) {
		return nil
	}
	payLogModel := new(models.PayLogModel).Init()
	payLogModel.Insert(map[string]interface{}{
		payLogModel.Field.F_order_sn:            payInfo.OrderSn,
		payLogModel.Field.F_pay_channel:         payInfo.PayChannel,
		payLogModel.Field.F_pay_type:            payType,
		payLogModel.Field.F_chose_pay_type:      payInfo.ChosePayType,
		payLogModel.Field.F_real_amount:         payInfo.RealAmount,
		payLogModel.Field.F_insure_amount:       payInfo.InsureAmount,
		payLogModel.Field.F_renew_insure_amount: payInfo.RenewInsureAmount,
		payLogModel.Field.F_platform_amount:     payInfo.PlatformAmount,
		payLogModel.Field.F_bus_amount:          payInfo.BusAmount,
		payLogModel.Field.F_insurance_channel:   payInfo.InsuranceChannel,
		payLogModel.Field.F_create_time:         time.Now().Unix(),
	})
	//杉德支付的二维码支付链接支付宝和微信相同，为了解决相同订单号重复提交，把ChosePayType改成0
	if payInfo.PayChannel == order2.PAY_CHANNEL_sand {
		if payInfo.ChosePayType == order2.CHOSE_PAY_TYPE_SAND_ALI || payInfo.ChosePayType == order2.CHOSE_PAY_TYPE_SAND_WX {
			payInfo.ChosePayType = 0
		}
	}
	key := fmt.Sprintf(constkey.PAY_CACHE, payInfo.OrderSn, payType, payInfo.PayChannel, payInfo.ChosePayType)
	return redis.RedisGlobMgr.Set(key, data, kcgin.AppConfig.DefaultInt64("pay.timeout", 1800))
}

// 支付成功后记账
func (p *PayLogic) PayAgent(ctx context.Context, orderSn string) (err error) {
	info, err := p.PayInfo(orderSn)
	if err != nil {
		return err
	}

	rpcOrderPay := new(order.OrderPay).Init()
	bill := order2.ReplyGetOrderSplitBill{}
	if err := rpcOrderPay.GetOrderSplitBill(context.Background(), &info.OrderSn, &bill); err != nil {
		return err
	}
	payLib, err := pay2.GetPay(info.PayChannel)

	//如果是平安银行渠道和ping++,新大陆的，不需要执行代付
	if info.PayChannel != order2.PAY_CHANNEL_pingan && info.PayChannel != order2.PAY_CHANNEL_pingpp && info.PayChannel != order2.PAY_CHANNEL_xindalu {
		// 记录待清算信息
		busClearingModel := new(models.BusClearingModel).Init()
		busClearingModel.Model.Begin()
		defer func() {
			if err != nil {
				busClearingModel.Model.RollBack()
			} else {
				busClearingModel.Model.Commit()
			}
		}()
		err = p.agent(payLib, busClearingModel, info, &bill)
		if err != nil {
			return err
		}
	}

	// 支付资金出入账记录
	fund := (*payLib).PayFund(info, &bill)
	rpcFund := []bus2.FundRecordItem{}
	for _, val := range fund {
		amount := decimal.RequireFromString(val.Amount)
		if !amount.IsZero() {
			rpcFund = append(rpcFund, val)
		}
	}
	rpcBusFund := new(bus.Fund).Init()
	reply := false
	if err := rpcBusFund.PayCharge(ctx, &bus2.FundRecord{
		BusId:          bill.BusId,
		FundRecordList: rpcFund,
	}, &reply); err != nil {
		return err
	}
	return err
}

// 待结算信息
func (p *PayLogic) agent(payLib *pay2.Pay, busClearingModel *models.BusClearingModel, info *pay.PayNotify, bill *order2.ReplyGetOrderSplitBill) (err error) {
	// 商户待结算信息
	billDate, err := strconv.Atoi(time.Now().Add(time.Hour * 24).Format("20060102"))
	if err != nil {
		return err
	}
	agentId, err := p.busAgent(busClearingModel, bill.BusId, billDate, decimal.NewFromFloat(bill.BusAmount), decimal.NewFromFloat(bill.DepositAmount), info.PayChannel)
	logs.Info("agentId=", agentId)
	if err != nil {
		return err
	}
	// 关联表记录
	busClearingOrderRealationModel := new(models.BusClearingOrderRealationModel).Init(busClearingModel.Model.GetOrmer())
	insertId := busClearingOrderRealationModel.Insert(map[string]interface{}{
		busClearingOrderRealationModel.Field.F_clear_id:    agentId,
		busClearingOrderRealationModel.Field.F_order_sn:    info.OrderSn,
		busClearingOrderRealationModel.Field.F_pay_sn:      info.PaySn,
		busClearingOrderRealationModel.Field.F_create_time: time.Now().Local().Unix(),
	})
	logs.Info("insertId=", insertId)
	logs.Info(busClearingOrderRealationModel.Model.GetLastSql())
	logs.Info(map[string]interface{}{
		busClearingOrderRealationModel.Field.F_clear_id:    agentId,
		busClearingOrderRealationModel.Field.F_order_sn:    info.OrderSn,
		busClearingOrderRealationModel.Field.F_pay_sn:      info.PaySn,
		busClearingOrderRealationModel.Field.F_create_time: time.Now().Local().Unix(),
	})
	if insertId == 0 {
		return toolLib.CreateKcErr(_const.PAY_ERROR)
	}
	// 平台待结算信息
	if decimal.NewFromFloat(bill.PlatformAmount).Cmp(decimal.Zero) == 1 {
		if err = new(fund.PlatformFundLogic).BusPay(bill.BusId, info.OrderSn, info.PayChannel, decimal.NewFromFloat(bill.PlatformAmount).String(), busClearingModel.Model.GetOrmer()); err != nil {
			return err
		}
	}
	// 保险公司待结算信息
	if decimal.NewFromFloat(bill.InsureAmount).Cmp(decimal.Zero) == 1 {
		insureOrderModel := new(models.InsureOrderModel).Init(busClearingModel.Model.GetOrmer())
		insert := 0
		if (*payLib).GetInsureFund() {
			insureClearingModel := new(models.InsureClearingModel).Init(busClearingModel.Model.GetOrmer())
			insureId, err := p.insureAgent(insureClearingModel, bill.InsuranceChannel, billDate, decimal.NewFromFloat(bill.InsureAmount), info.PayChannel)
			if err != nil {
				return err
			}
			insert = insureOrderModel.Insert(map[string]interface{}{
				insureOrderModel.Field.F_order_sn:        info.OrderSn,
				insureOrderModel.Field.F_pay_sn:          info.PaySn,
				insureOrderModel.Field.F_insure_id:       bill.InsuranceChannel,
				insureOrderModel.Field.F_total_amount:    info.PayAmount,
				insureOrderModel.Field.F_amount:          bill.InsureAmount,
				insureOrderModel.Field.F_create_time:     time.Now().Unix(),
				insureOrderModel.Field.F_pay_channel:     info.PayChannel,
				insureOrderModel.Field.F_clearing_id:     insureId,
				insureOrderModel.Field.F_clearing_status: pay.CLEAR_STATUS_ing,
			})
		} else {
			insert = insureOrderModel.Insert(map[string]interface{}{
				insureOrderModel.Field.F_order_sn:        info.OrderSn,
				insureOrderModel.Field.F_pay_sn:          info.PaySn,
				insureOrderModel.Field.F_insure_id:       bill.InsuranceChannel,
				insureOrderModel.Field.F_total_amount:    info.PayAmount,
				insureOrderModel.Field.F_amount:          bill.InsureAmount,
				insureOrderModel.Field.F_create_time:     time.Now().Unix(),
				insureOrderModel.Field.F_pay_channel:     info.PayChannel,
				insureOrderModel.Field.F_clearing_status: pay.CLEAR_STATUS_suc,
			})
		}
		if insert <= 0 {
			return toolLib.CreateKcErr(_const.PAY_ERROR)
		}

	}
	// 续保公司待结算信息
	if decimal.NewFromFloat(bill.RenewInsureAmount).Cmp(decimal.Zero) == 1 {
		// 获取续保id类型
		renewInsureId := 0
		renewInsureOrderModel := new(models.RenewInsureOrderModel).Init(busClearingModel.Model.GetOrmer())
		insert := 0
		if (*payLib).GetInsureFund() {
			renewInsureClearingModel := new(models.RenewInsureClearingModel).Init(busClearingModel.Model.GetOrmer())
			insureId, err := p.renewInsureAgent(renewInsureClearingModel, renewInsureId, billDate, decimal.NewFromFloat(bill.RenewInsureAmount), info.PayChannel)
			if err != nil {
				return err
			}
			insert = renewInsureOrderModel.Insert(map[string]interface{}{
				renewInsureOrderModel.Field.F_order_sn:        info.OrderSn,
				renewInsureOrderModel.Field.F_pay_sn:          info.PaySn,
				renewInsureOrderModel.Field.F_renew_insure_id: renewInsureId,
				renewInsureOrderModel.Field.F_total_amount:    info.PayAmount,
				renewInsureOrderModel.Field.F_amount:          bill.RenewInsureAmount,
				renewInsureOrderModel.Field.F_create_time:     time.Now().Unix(),
				renewInsureOrderModel.Field.F_pay_channel:     info.PayChannel,
				renewInsureOrderModel.Field.F_clearing_id:     insureId,
				renewInsureOrderModel.Field.F_clearing_status: pay.CLEAR_STATUS_ing,
			})
		} else {
			insert = renewInsureOrderModel.Insert(map[string]interface{}{
				renewInsureOrderModel.Field.F_order_sn:        info.OrderSn,
				renewInsureOrderModel.Field.F_pay_sn:          info.PaySn,
				renewInsureOrderModel.Field.F_renew_insure_id: renewInsureId,
				renewInsureOrderModel.Field.F_total_amount:    info.PayAmount,
				renewInsureOrderModel.Field.F_amount:          bill.RenewInsureAmount,
				renewInsureOrderModel.Field.F_create_time:     time.Now().Unix(),
				renewInsureOrderModel.Field.F_pay_channel:     info.PayChannel,
				renewInsureOrderModel.Field.F_clearing_status: pay.CLEAR_STATUS_suc,
			})
		}
		if insert <= 0 {
			return toolLib.CreateKcErr(_const.PAY_ERROR)
		}
	}

	return nil
}

// 记录待清算信息
func (p *PayLogic) busAgent(busClearingModel *models.BusClearingModel, busId int, billDate int, amount decimal.Decimal, depositoryAmount decimal.Decimal, agentType int) (int, error) {
	res := busClearingModel.FindByBusIdAndBillDate(busId, billDate)
	agentId := 0
	if len(res) > 0 {
		row, err := busClearingModel.UpdateByBusIdAndBillDate(busId, billDate, map[string]interface{}{
			busClearingModel.Field.F_amount:            []interface{}{"inc", amount.String()},
			busClearingModel.Field.F_depository_amount: []interface{}{"inc", depositoryAmount.String()},
			busClearingModel.Field.F_usable_amount:     []interface{}{"inc", amount.Sub(depositoryAmount).String()},
		})
		if err != nil {
			return 0, err
		}
		if row != 1 {
			return 0, toolLib.CreateKcErr(_const.NETWORK_ERROR)
		}
		agentId, _ = strconv.Atoi(res[busClearingModel.Field.F_id].(string))
	} else {
		agentId = busClearingModel.Insert(map[string]interface{}{
			busClearingModel.Field.F_bus_id:            busId,
			busClearingModel.Field.F_bill_date:         billDate,
			busClearingModel.Field.F_amount:            amount.String(),
			busClearingModel.Field.F_depository_amount: depositoryAmount.String(),
			busClearingModel.Field.F_usable_amount:     amount.Sub(depositoryAmount).String(),
			busClearingModel.Field.F_agent_type:        agentType,
			busClearingModel.Field.F_create_time:       time.Now().Unix(),
		})
		if agentId <= 0 {
			return 0, toolLib.CreateKcErr(_const.NETWORK_ERROR)
		}
	}
	return agentId, nil
}

// 记录待清算信息
func (p *PayLogic) insureAgent(insureClearingModel *models.InsureClearingModel, insureId int, billDate int, amount decimal.Decimal, agentType int) (int, error) {
	res := insureClearingModel.FindByBusIdAndBillDate(insureId, billDate)
	agentId := 0
	if len(res) > 0 {
		row, err := insureClearingModel.UpdateByInsureIdAndBillDate(insureId, billDate, map[string]interface{}{
			insureClearingModel.Field.F_amount: []interface{}{"inc", amount.String()},
		})
		if err != nil {
			return 0, err
		}
		if row != 1 {
			return 0, toolLib.CreateKcErr(_const.NETWORK_ERROR)
		}
		agentId, _ = strconv.Atoi(res[insureClearingModel.Field.F_id].(string))
	} else {
		agentId = insureClearingModel.Insert(map[string]interface{}{
			insureClearingModel.Field.F_insure_id:   insureId,
			insureClearingModel.Field.F_bill_date:   billDate,
			insureClearingModel.Field.F_amount:      amount.String(),
			insureClearingModel.Field.F_agent_type:  agentType,
			insureClearingModel.Field.F_create_time: time.Now().Unix(),
		})
		if agentId <= 0 {
			return 0, toolLib.CreateKcErr(_const.NETWORK_ERROR)
		}
	}
	return agentId, nil
}

// 记录待清算信息
func (p *PayLogic) renewInsureAgent(renewInsureClearingModel *models.RenewInsureClearingModel, renewInsureId int, billDate int, amount decimal.Decimal, agentType int) (int, error) {
	res := renewInsureClearingModel.FindByBusIdAndBillDate(renewInsureId, billDate)
	agentId := 0
	if len(res) > 0 {
		row, err := renewInsureClearingModel.UpdateByInsureIdAndBillDate(renewInsureId, billDate, map[string]interface{}{
			renewInsureClearingModel.Field.F_amount: []interface{}{"inc", amount.String()},
		})
		if err != nil {
			return 0, err
		}
		if row != 1 {
			return 0, toolLib.CreateKcErr(_const.NETWORK_ERROR)
		}
		agentId, _ = strconv.Atoi(res[renewInsureClearingModel.Field.F_id].(string))
	} else {
		agentId = renewInsureClearingModel.Insert(map[string]interface{}{
			renewInsureClearingModel.Field.F_renew_insure_id: renewInsureId,
			renewInsureClearingModel.Field.F_bill_date:       billDate,
			renewInsureClearingModel.Field.F_amount:          amount.String(),
			renewInsureClearingModel.Field.F_agent_type:      agentType,
			renewInsureClearingModel.Field.F_create_time:     time.Now().Unix(),
		})
		if agentId <= 0 {
			return 0, toolLib.CreateKcErr(_const.NETWORK_ERROR)
		}
	}
	return agentId, nil
}

/**
 * 资金清分【商家】
 * @return void
 */
func (p *PayLogic) AngelChannel() error {
	busClearingModel := new(models.BusClearingModel).Init()
	mPay := map[int]*pay2.Pay{}
	timeDate := time.Now().Format("20060102")
	for true {
		lists := busClearingModel.Lists(timeDate, 0, 50)
		if len(lists) == 0 {
			break
		}
		for _, list := range lists {
			channel, err := strconv.Atoi(list[busClearingModel.Field.F_agent_type].(string))
			if err != nil {
				continue
			}
			payType, ok := mPay[channel]
			if !ok {
				payType, err = pay2.GetPay(channel)
				if err != nil {
					continue
				}
				mPay[channel] = payType
			}
			// 各渠道分账前置处理
			busClearingModel.Model.Begin()
			agentId, err := (*payType).AgentChannel(busClearingModel, list)
			if err != nil || agentId == 0 {
				busClearingModel.Model.RollBack()
				continue
			}
			// 商户单日分账汇总表处理
			upRes, err := busClearingModel.UpdateByIdAndStatus(list[busClearingModel.Field.F_id], pay.CLEAR_STATUS_none, map[string]interface{}{
				busClearingModel.Field.F_agent_id: agentId,
				busClearingModel.Field.F_status:   pay.CLEAR_STATUS_ing,
			})
			if err != nil || upRes != 1 {
				busClearingModel.Model.RollBack()
				continue
			}
			busClearingModel.Model.Commit()
		}
		return nil
	}
	return nil
}

/**
 * 资金清分【平台】
 * @return void
 */
func (p *PayLogic) AngelChannelPlat() error {
	platClearingModel := new(models.PlatformClearingModel).Init()
	mPay := map[int]*pay2.Pay{}
	timeDate := time.Now().Format("20060102")
	for true {
		lists := platClearingModel.Lists(timeDate, 0, 50)
		if len(lists) == 0 {
			break
		}
		for _, list := range lists {
			channel, err := strconv.Atoi(list[platClearingModel.Field.F_agent_type].(string))
			if err != nil {
				continue
			}
			payType, ok := mPay[channel]
			if !ok {
				payType, err = pay2.GetPay(channel)
				if err != nil {
					continue
				}
				mPay[channel] = payType
			}
			// 各渠道分账前置处理
			platClearingModel.Model.Begin()
			agentId, err := (*payType).AgentChannelPlat(platClearingModel, list)
			if err != nil || agentId == 0 {
				platClearingModel.Model.RollBack()
				continue
			}
			//平台手续费单日分账汇总表处理
			upRes, err := platClearingModel.UpdateByIdAndStatus(list[platClearingModel.Field.F_id], pay.CLEAR_STATUS_none, map[string]interface{}{
				platClearingModel.Field.F_agent_id: agentId,
				platClearingModel.Field.F_status:   pay.CLEAR_STATUS_ing,
			})
			if err != nil || upRes != 1 {
				platClearingModel.Model.RollBack()
				continue
			}
			platClearingModel.Model.Commit()
		}
		return nil
	}
	return nil
}

/**
* 资金清分【保险-正常】
* @return void
 */
func (p *PayLogic) AngelChannelInsure() error {
	insureClearingModel := new(models.InsureClearingModel).Init()
	mPay := map[int]*pay2.Pay{}
	timeDate := time.Now().Format("20060102")
	for true {
		lists := insureClearingModel.Lists(timeDate, 0, 50)
		if len(lists) == 0 {
			break
		}
		for _, list := range lists {
			channel, err := strconv.Atoi(list[insureClearingModel.Field.F_agent_type].(string))
			if err != nil {
				continue
			}
			payType, ok := mPay[channel]
			if !ok {
				payType, err = pay2.GetPay(channel)
				if err != nil {
					continue
				}
				mPay[channel] = payType
			}
			// 各渠道分账前置处理
			insureClearingModel.Model.Begin()
			agentId, err := (*payType).AgentChannelInsure(insureClearingModel, list)
			if err != nil || agentId == 0 {
				insureClearingModel.Model.RollBack()
				continue
			}
			//平台手续费单日分账汇总表处理
			upRes, err := insureClearingModel.UpdateByIdAndStatus(list[insureClearingModel.Field.F_id], pay.CLEAR_STATUS_none, map[string]interface{}{
				insureClearingModel.Field.F_agent_id: agentId,
				insureClearingModel.Field.F_status:   pay.CLEAR_STATUS_ing,
			})
			if err != nil || upRes != 1 {
				insureClearingModel.Model.RollBack()
				continue
			}
			insureClearingModel.Model.Commit()
		}
		return nil
	}
	return nil
}

/**
* 资金清分【保险-续保】
* @return void
 */
func (p *PayLogic) AngelChannelRenewInsure() error {
	renewInsureClearingModel := new(models.RenewInsureClearingModel).Init()
	mPay := map[int]*pay2.Pay{}
	timeDate := time.Now().Format("20060102")
	for true {
		lists := renewInsureClearingModel.Lists(timeDate, 0, 50)
		if len(lists) == 0 {
			break
		}
		for _, list := range lists {
			channel, err := strconv.Atoi(list[renewInsureClearingModel.Field.F_agent_type].(string))
			if err != nil {
				continue
			}
			payType, ok := mPay[channel]
			if !ok {
				payType, err = pay2.GetPay(channel)
				if err != nil {
					continue
				}
				mPay[channel] = payType
			}
			// 各渠道分账前置处理
			renewInsureClearingModel.Model.Begin()
			agentId, err := (*payType).AgentChannelRenewInsure(renewInsureClearingModel, list)
			if err != nil || agentId == 0 {
				renewInsureClearingModel.Model.RollBack()
				continue
			}
			//平台手续费单日分账汇总表处理
			upRes, err := renewInsureClearingModel.UpdateByIdAndStatus(list[renewInsureClearingModel.Field.F_id], pay.CLEAR_STATUS_none, map[string]interface{}{
				renewInsureClearingModel.Field.F_agent_id: agentId,
				renewInsureClearingModel.Field.F_status:   pay.CLEAR_STATUS_ing,
			})
			if err != nil || upRes != 1 {
				renewInsureClearingModel.Model.RollBack()
				continue
			}
			renewInsureClearingModel.Model.Commit()
		}
		return nil
	}
	return nil
}

// 异步回调开发调试版本
func (p *PayLogic) NotifyDev(ctx context.Context, orderSn string, payAmount, payFee float64) error {
	if kcgin.AppConfig.String("runmode") == "prod" {
		return nil
	}
	payNotifyModel := new(models.PayNotifyModel).Init()
	if len(payNotifyModel.GetByOrderSn(orderSn)) == 0 {
		payNotifyModel.Insert(map[string]interface{}{
			payNotifyModel.Field.F_order_sn:    orderSn,
			payNotifyModel.Field.F_pay_sn:      orderSn,
			payNotifyModel.Field.F_pay_channel: order2.PAY_CHANNEL_sand,
			payNotifyModel.Field.F_pay_type:    order2.PAY_TYPE_YUAN,
			payNotifyModel.Field.F_pay_amount:  payAmount,
			payNotifyModel.Field.F_pay_fee:     payFee,
			payNotifyModel.Field.F_pay_time:    time.Now().Unix() - 1,
			payNotifyModel.Field.F_pay_status:  pay.PAY_Suc,
			payNotifyModel.Field.F_create_time: time.Now().Unix(),
			payNotifyModel.Field.F_pay_raw:     "",
		})
		rpcTaskPay := new(pay3.Pay).Init()
		res := false
		if err := rpcTaskPay.PaySuc(ctx, &orderSn, &res); err != nil {
			return err
		}
	}
	return nil
}
